var express = require('express');
var request = require("request");
var Q = require("q");
var app = express.Router();

var base_url = "http://dcr-api.poolgpu.com/api";
var getblocknum = function(opt) {
  var pr = Q.defer();
  request(opt, function(error, response, body) {
    if(body) {
      pr.resolve(body);
    }
  });
  return pr.promise;
}

app.get("/stats.shtml", function(req, res) {
  var ops = {
    url: base_url + "/CoinStatus?algo=b2x",
    method: req.method.toString(),
    json: true
  }
  request(ops, function(error, response, body) {
    console.log(body);
    if(!body) {
      res.json({
        error: true
      })
      return
    }
    var poolData = body.b2x;
    res.json(poolData);
  });
});
app.get("/allblocksnum.shtml", function(req, res) {
  var ethPr = getblocknum({
    url: "http://eth-api.poolgpu.com/api/blocks",
    method: req.method.toString(),
    json: true
  });
  var etcPr = getblocknum({
    url: "http://etc.poolgpu.com/api/blocks",
    method: req.method.toString(),
    json: true
  });
  var expPr = getblocknum({
    url: "http://exp.poolgpu.com/api/blocks",
    method: req.method.toString(),
    json: true
  });
  var zecPr = getblocknum({
    url: "http://zec.poolgpu.com/api/block_list",
    method: req.method.toString(),
    json: true
  });
  var scPr = getblocknum({
    url: "http://sia-api.poolgpu.com/api/blocks",
    method: req.method.toString(),
    json: true
  });
  var btxPr = getblocknum({
    url: "http://btg.poolgpu.com:5005/blocklist.shtml",
    method: req.method.toString(),
    json: true
  });
  var dcrPr = getblocknum({
    url: "http://dcr.poolgpu.com:5556/blocklist.shtml",
    method: req.method.toString(),
    json: true
  });
  Q.all([ethPr, etcPr, expPr, zecPr, scPr, btxPr, dcrPr]).then(function(result) {
    var ethdata = parseInt(result[0].immatureTotal) + parseInt(result[0].candidatesTotal);
    var etcdata = parseInt(result[1].immatureTotal) + parseInt(result[1].candidatesTotal);
    var expdata = parseInt(result[2].immatureTotal) + parseInt(result[2].candidatesTotal);
    var zecdata = parseInt(result[3].pools.zcash.blocks.pending);
    var scdata = parseInt(result[4].immatureTotal) + parseInt(result[4].candidatesTotal);
    var btxtemp = result[5].data;
    var btxdata = 0;
    for(var i = 0; i < btxtemp.length; i ++) {
      if(btxtemp[i].category == "immature") btxdata++;
    }
    var dcrtemp = result[6].data;
    var dcrdata = 0;
    for(var i = 0; i < dcrtemp.length; i ++) {
      if(dcrtemp[i].category == "immature") dcrdata++;
    }
    res.json({
      ethnum: ethdata,
      etcnum: etcdata,
      expnum: expdata,
      zecnum: zecdata,
      scnum: scdata,
      btxnum: btxdata,
      dcrnum: dcrdata
    });
  });
});
app.get("/minerlist.shtml", function(req, res) {
  var ops = {
    url: base_url + "/MinersList?algo=b2x",
    method: req.method.toString(),
    json: true
  }
  request(ops, function(error, response, body) {
    if(!body) {
      res.json({
        error: true
      })
      return
    }
    var minersData = body;
    res.json(minersData);
  });
});
app.get("/pool_payments.shtml", function(req, res) {
  var ops = {
    url: base_url + "/pool_payments?algo=b2x",
    method: req.method.toString(),
    json: true
  }
  request(ops, function(error, response, body) {
    if(!body) {
      res.json({
        error: true
      })
      return
    }
    var minersData = {
      datas: body.zcash
    }
    res.json(minersData);
  });
});
app.get("/blocklist.shtml", function(req, res) {
  var ops = {
    url: base_url + "/blocks?algo=b2x",
    method: req.method.toString(),
    json: true
  }
  request(ops, function(error, response, body) {
    if(!body) {
      res.json({
        error: true
      })
      return
    }
    var blockData = {
      code: 0,
      data: body.data
    }
    res.json(blockData);
  });
});

app.get("/minerDetail.shtml", function(req, res) {
  var ops = {
    url: base_url + "/walletEx?algo=b2x&address=" + req.query.addr,
    method: req.method.toString(),
    json: true
  }
  console.log(ops)
  request(ops, function(error, response, body) {
    if(!body) {
      res.json({
        error: true
      })
      return
    }
    //console.log(body);
    /*var miner = {
      addr: body.miner,
      hr: getReadableHashRateString(body.totalHash, true),
      balance: body.balance,
      paid: body.paid
    }*/
    res.json({
      minerInfo: body
    });
  });
})

app.get("/poolHistory.shtml", function(req, res) {
  var ops = {
    url: "http://dcr-api.poolgpu.com//site/graph_hashrate_results?algo=b2x",
    method: req.method.toString(),
    json: true
  }
  request(ops, function(error, response, body) {
    if(!body) {
      res.json({
        error: true
      })
      return
    }
    var hrs = [],
      times = [];
    for(var i = 0; i < body[1].length; i++) {
        hrs.push(body[1][i][1]);
        times.push(body[1][i][0]);
    }
    res.json({
      hrs: hrs,
      times: times
    });
  });
});

app.get("/getluck.shtml", function(req, res) {
  var ops = {
    url: base_url + "/luck_rate?algo=b2x",
    method: req.method.toString(),
    json: true
  }
  request(ops, function(error, response, body) {
    if(!body) {
      res.json({
        error: true
      });
      return;
    }
    res.json({
      datas: body.zcash
    });
  });
});

function getReadableHashRateString(hashrate, unit) {
  unit = unit || false
  hashrate = (hashrate * 2);
  if(hashrate < 1000000) {
    if(unit) {
      return(Math.round(hashrate / 1000) / 1000).toFixed(2) + ' Sol/s';
    } else {
      return(Math.round(hashrate / 1000) / 1000).toFixed(2);
    }
  }
  if(unit) {
    var byteUnits = [' Sol/s', ' KSol/s', ' MSol/s', ' GSol/s', ' TSol/s', ' PSol/s'];
    var i = Math.floor((Math.log(hashrate / 1000) / Math.log(1000)) - 1);
    hashrate = (hashrate / 1000) / Math.pow(1000, i + 1);
    return hashrate.toFixed(2) + byteUnits[i];
  } else {
    try {
      hashrate = ((hashrate / 1000) / Math.pow(1000, 1) / 1000);
    } catch(e) {
      hashrate = 0
    }
    return hashrate.toFixed(2);
  }
}

function dateFormat(time, fmt) {
  if(!time) {
    return "";
  }
  fmt = fmt || "yyyy-MM-dd hh:mm:ss";
  var d = new Date(time);
  var o = {
    "M+": d.getMonth() + 1, //月份   
    "d+": d.getDate(), //日   
    "h+": d.getHours(), //小时   
    "m+": d.getMinutes(), //分   
    "s+": d.getSeconds(), //秒   
    "q+": Math.floor((d.getMonth() + 3) / 3), //季度   
    "S": d.getMilliseconds() //毫秒   
  };
  if(/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
  for(var k in o)
    if(new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}
module.exports = app;